<template>

    <el-dialog :title="$root.lang.userinfo.activateSafeMailbox" :visible.sync="showDialog" width="50%" @close="closeDialog"  :close-on-click-modal="false" :close-on-press-escape="false" >
      <el-form @submit.native.prevent class="change-password" :model="securityEmailForm"  ref="securityEmailForm" :rules="activesecurityEmailRules" size="small" label-position="right" :label-width="formLabelWidth">
        <el-form-item :label="$root.lang.userinfo.captcha" prop="captcha" class="form-captcha" align="left">
          <el-input type="text" v-model="securityEmailForm.captcha"></el-input>
          <img @click="getSecurityEmailCaptcha()"  :src="securityEmailCode" :title="$root.lang.forgotStep1.captchaTip"/>
          <p class="form-item-tip">{{ $root.lang.userinfo.captchaTip }}</p>
        </el-form-item>
        <el-form-item :label="$root.lang.userinfo.securityEmailActiveCode" :label-width="formLabelWidth" prop="securityEmailActiveCode"  ref="securityEmailActiveCodeForm">
          <el-input  v-model="securityEmailForm.securityEmailActiveCode" @keyup.enter.native="toActiveSecurityEmail()" auto-complete="off"></el-input>
          <el-button style="margin-left:12px;" type="primary" @click="doActiveCode()" :disabled="showCount" ><span v-if="!showCount">{{ $root.lang.userinfo.backGet }}</span> <span v-if="showCount">{{ count }}s后重新获取</span></el-button>
        </el-form-item>
        <el-form-item>
          <el-button class="dialog-btn" @click="toActiveSecurityEmail()" :loading="loading" type="primary" >{{ $root.lang.userinfo.editLoginEmail.confirm }}</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>


</template>

<script>
export default {
  name: 'activeSafeEmail',
  data() {
    return {
    	showDialog: this.show,
    	showCount: false,
    	securityEmailCode: '',
    	timer: null,
    	count:0,
    	loading: false,
    	formLabelWidth: '120px',
    	updateRecordNumber: '',
    	securityEmailForm:{
    		captcha: '',
    		securityEmailActiveCode: ''
    	},
    	activesecurityEmailRules: {
        captcha: [{ required: true, message: this.$root.lang.userinfo.editLoginEmail.editRule.captcha, trigger: 'blur' }],
        securityEmailActiveCode: [{ required: true, message: this.$root.lang.userinfo.editLoginEmail.editRule.emailActiveCode, trigger: 'blur' }]
      },
    }
  },
  watch: {
  	show: function (value) {
      if(this.$refs['securityEmailForm']) this.$refs['securityEmailForm'].resetFields()
      this.showDialog = value
    },
  },
   props: {
    show: {
      type: Boolean,
      default: false
    },
  },
  methods: {
  	closeDialog() {
      this.$emit('editEmailReceive',{
        key: 'activeSecurityCode',
        value: this.showDialog
      })
    },
    getCode(){
     const TIME_COUNT = 60;
     if (!this.timer) {
       this.count = TIME_COUNT;
       this.showCount = true;
       this.timer = setInterval(() => {
       if (this.count > 0 && this.count <= TIME_COUNT) {
         this.count--;
        } else {
         this.showCount = false;
         clearInterval(this.timer);
         this.timer = null;
        }
       }, 1000)
      }
    },
    getSecurityEmailCaptcha() {
      const suffix = process.env.API_1 === '/' ? '' : process.env.API_1;
      this.securityEmailCode= suffix +'/api/user/captcha/activate/security/email?'+Math.random()
    },
    cancelFieldValidate () {
      this.$refs['securityEmailActiveCodeForm'].clearValidate() // 清除年龄的验证
    },
    doActiveCode() {
    	delete this.securityEmailForm['securityEmailActiveCode']
      delete this.activesecurityEmailRules['securityEmailActiveCode']
    	this.$refs['securityEmailForm'].validate((valid) => {
        if(valid) {
          this.request({
              url: '/api/user/activate/security/email/code',
              method: 'POST',
              data: this.$root.optionProcess(this['securityEmailForm'])
            }).then(response => {
            	this.getCode()
              this.updateRecordNumber = response.result.updateRecordNumber
            }).catch(error => {
							this.getSecurityEmailCaptcha()
              this.$message({
                message: error.errmsg,
                type: 'error',
                duration: 3 * 1000
              })
          })
        }else{
          return false
        }
      })
    },
    toActiveSecurityEmail() {
      this.activesecurityEmailRules['securityEmailActiveCode'] = [{ required: true, message: this.$root.lang.userinfo.editLoginEmail.editRule.emailActiveCode, trigger: 'blur' }]
    	let code = this.securityEmailForm.securityEmailActiveCode
      let json = {
        code: code,
        updateRecordNumber: this.updateRecordNumber
      }
      this.$refs['securityEmailForm'].validate((valid) => {
        if(valid) {
          this.loading = true
          this.request({
              url: '/api/user/activate/security/email',
              method: 'POST',
              data: this.$root.optionProcess(json)
            }).then(response => {
                this.loading = false
                this.$message({
                  message:  this.$root.lang.confirm.activeSuccess,
                  type: 'success',
                  duration: 3 * 1000
                })
                this.showDialog = false
        				this.$emit('reload')
                this.$refs["securityEmailForm"].resetFields()
            }).catch(error => {
              this.loading = false
              this.$message({
                message: error.errmsg,
                type: 'error',
                duration: 3 * 1000
              })
          })
        }else{
          return false
        }
      })
    }
  },
  created() {
  	this.getSecurityEmailCaptcha()
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
		.el-input{
      display: inline-block;
      width: 69.5%;
      float: left;
    }
    .form-item-tip {
    	float:left;
    }
   .form-captcha {
    .el-input{
      display: inline-block;
      width: 69.5%;
      float: left;
    }
    img {
      height: 32px;
      width: 15%;
      border-radius: 4px;
      cursor: pointer;
      float: left;
      margin-left: 8px;
    }
  }
</style>